package com.springboot.Service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.springboot.Service.ProvinceService;
import com.springboot.domain.Province;
import org.springframework.stereotype.Service;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.URL;
import java.net.URLConnection;
import java.util.*;

/**
 * @author 权哥
 * @version 1.0
 * @date 2022/5/5 19:08
 */
@Service
public class ProvinceListimpl implements ProvinceService {
    String provinceUrl="https://api.inews.qq.com/newsqa/v1/query/pubished/daily/list?province=";
    String dayUrl="&limit=";

    @Override
    public ArrayList<Province> ProvinceList(String provinceName, int days) throws IOException {
        ArrayList<Province> provinceList = new ArrayList<Province>();
        String url = provinceUrl + provinceName + dayUrl + days + "&";
        //2.模拟发送请求
        URLConnection oc = new URL(url).openConnection();
        //3.获取输入流
        InputStream in = oc.getInputStream();
        //4.创建一个字符流写入文件
        BufferedReader br = new BufferedReader(new InputStreamReader(in, "UTF-8"));
        //5.读取字符，一行一行的读取
        String all = "";
        while (true) {
            //一次性读取一行数据
            String rl = br.readLine();
            if (rl == null) {
                break;//如果读取的内容为空，就跳出循环
            }

            all += rl;
        }
        System.out.println(all);

        //解析json

        JSONObject json = (JSONObject) JSON.parse(all);

        JSONArray data = json.getJSONArray("data");
        System.out.println(data.size());
        for (int i = 0; i < data.size(); i++) {
            Province province = new Province();

            province.setDate(data.getJSONObject(i).getString("_mtime").substring(0,10));
            province.setNewConfirm(Integer.parseInt(data.getJSONObject(i).getString("newConfirm")));
            province.setConfirm(Integer.parseInt(data.getJSONObject(i).getString("confirm")));
            province.setHeal(Integer.parseInt(data.getJSONObject(i).getString("heal")));
            province.setDead(Integer.parseInt(data.getJSONObject(i).getString("dead")));

            provinceList.add(province);
        }


        return provinceList;
    }

}
